package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jzo2o.api.publics.MapApi;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.*;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.*;

import com.jzo2o.mvc.utils.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


/**
 * <p>
 * 服务人员/机构表 银行账户信息 服务实现类
 * </p>
 * @author itcast
 * @since 2023-07-17
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements BankAccountService {



    @Override
    public void addBankAccountInfo(BankAccountUpsertReqDTO dto) {
        if(ObjectUtils.isEmpty(dto)){
            throw new CommonException("参数异常");
        }
        //数据转换
        BankAccount bankAccount = new BankAccount();
        BeanUtils.copyProperties(dto, bankAccount);
        //先判断是否已经绑定过银行账户
        try{
            BankAccount one = this.lambdaQuery().eq(BankAccount::getId, UserContext.currentUserId()).one();
            if(!ObjectUtils.isEmpty(one)){
                //已存在绑定账户则更新绑定的账户信息
                this.lambdaUpdate().eq(BankAccount::getId, UserContext.currentUserId())
                        .update(bankAccount);
                return;
            }
        }catch (Exception e){
            throw new CommonException("该账号已经存在两个及以上的银行账户绑定");
        }
        //若为绑定用户则新增
        bankAccount.setId(UserContext.currentUserId());
        this.save(bankAccount);
    }

    @Override
    public BankAccountResDTO findCurrentUserBankAccountInfo() {

        BankAccount one = null;
        try {
            one = this.lambdaQuery().eq(BankAccount::getId, UserContext.currentUserId()).one();
        } catch (Exception e) {
            throw new CommonException("该账号已经存在两个及以上的银行账户绑定");
        }
        if(ObjectUtils.isEmpty(one)){
            throw new CommonException("当前用户还未绑定银行账户");
        }
        BankAccountResDTO bankAccountResDTO = new BankAccountResDTO();
        BeanUtils.copyProperties(one, bankAccountResDTO);
        return bankAccountResDTO;

    }
}
